package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.utils.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description:
 * @author: dalao
 * @date: 2020/4/17-21:36
 * @Version: 1.0.0
 */
public class AuthorizeInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisUtils jedisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("我要进来咯~~~~~");
//        获取token , 无法直接获取本地的token , 需要从请求头中获取
        String token = request.getHeader("token");
//        判断是否为空,如果为空则返回false,去登录界面
        if(token==null||"".equals(token)||"null".equals(token)){
//            response.sendRedirect(request.getContextPath()+"/user/toLogin.do") 重定向写法
            goLogin(response);
            return false;
        }else{
//            从redis获取token,如果为空去登录
            String redisToken = jedisUtils.get(token);
            if(token==null){
                goLogin(response);
                return false;
            }
        }

        return true;
    }

    private void goLogin(HttpServletResponse response) throws IOException {
        Result result = new Result(false, "您还未登录,跳转至登录页面", 401);
//        通过response将result返回去
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result));
//        关流
        writer.close();

    }


}
